package cn.softgame.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 游戏服务器
 * @author lenovo
 *
 */
public class GameServer {
	private String host="localhost";
	private int port=8888;
	private ServerSocketChannel ssc;
	private int channels = 0;
	private int keys = 0;
	private int currentSelector = 0;
	public GameServer(){
		try {
			ssc = ServerSocketChannel.open();
			ssc.configureBlocking(false);
			InetSocketAddress address = new InetSocketAddress(host,port);
			ssc.socket().bind(address);
			
			Selector selector = Selector.open();
			SelectionKey sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
			printKeyInfo(sk);
			while(true){
				keys = selector.select();
				if(keys>0){
					Set<SelectionKey> selectedKeys = selector.selectedKeys();
					for(Iterator<SelectionKey> iter=selectedKeys.iterator();iter.hasNext();){
						sk = iter.next();
						printKeyInfo(sk);
						iter.remove();
						if(sk.isAcceptable()){
							Socket socket = ((ServerSocketChannel)sk.channel()).accept().socket();
							SocketChannel sc = socket.getChannel();
							sc.configureBlocking(false);
							sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
							System.out.println(++channels);
						}else{
							System.err.print("Channel not acceptable");
						}
					}
				}else{
					System.out.println("Select finished without any keys");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public GameServer(String host,int port){
		this.host=host;
		this.port=port;
	}
	
	private static void printKeyInfo(SelectionKey sk){
		String s = new String();
		s = "Att: " + (sk.attachment() == null ? "no" : "yes");
		s += ", Read: " + sk.isReadable();
		s += ", Acpt: " + sk.isAcceptable();
		s += ", Cnct: " + sk.isConnectable();
		s += ", Wrt: " + sk.isWritable();
		s += ", Valid: " + sk.isValid();
		s += ", Ops: " + sk.interestOps();
		System.out.println(s);
	}
	
	public static void main(String[] args) {
		GameServer server = new GameServer();
	}
}
